package com.example.servlet;

import com.example.dao.EquipDao;
import com.example.pojo.Equipment;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/doEquipment")
public class EquipmentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    EquipDao dao=new EquipDao();
    PrintWriter out = resp.getWriter();
        switch (req.getParameter("methods"))
   {
       case "add":
           Equipment equipment=new Equipment();
           SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日");
           try {
               equipment.setDate(format.parse(req.getParameter("date")));
               System.out.println(format.parse(req.getParameter("date")));
           } catch (ParseException e) {
               e.printStackTrace();
               System.err.println(e.toString());
           }
           equipment.setName(req.getParameter("name"));
           equipment.setCount(Integer.valueOf(req.getParameter("count")));
           if(dao.addEquip(equipment)) out.println("<h3>器材添加成功</h3>");
           else out.println("<h3>器材添加失败</h3>");
           break;
       case "use1":
           //使用
           if(dao.useEquip(Integer.valueOf(req.getParameter("id")),true))
               out.println("<h3>使用器材成功</h3>");
           else out.println("<h3>使用添加失败</h3>");
           break;
       case "use2":
           //归还
           if(dao.useEquip(Integer.valueOf(req.getParameter("id")),false))
               out.println("<h3>归还器材成功</h3>");
           else out.println("<h3>归还添加失败</h3>");
           break;
       case "delete":
           if(dao.deleteEquip(Integer.valueOf(req.getParameter("id"))))
               out.println("<h3>删除器材成功</h3>");
           else out.println("<h3>删除添加失败</h3>");
           break;
       default:
           break;
   }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
